﻿///***************************************************************
/// 시  스  템 : Updms.Mny
/// 단위시스템 : MNY
/// 계      층 : Presentation Layer
/// 프로그램명 : Mny1013m
/// 파  일  명 : Mny1013m.aspx.cs
/// 설      명 : 예산관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-12-15 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.SMGridView;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Mny.Exe;


namespace Updms.Mny
{
	public partial class Mny1013m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Mny1013m";
		public static readonly string gs_path_info = "/updms/Mny/" + PID + ".aspx";

		Global global = new Global();

		//검색
		protected string kw1 = "";	// 기준년월

		//메뉴 선택값
		protected string gs_sm = "";

		//합계
		decimal ld_pre_1_m = 0;
		decimal ld_pre_1_y = 0;
		decimal ld_pre_3_m_avg = 0;
		decimal ld_pre_12_m_avg = 0;
		
		decimal ld_amount = 0;

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetBaseYear();
			SetSearchParameter();
			SetYearlyRegYnList();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetTitle, SetClientScript

		#endregion

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			
			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_base_year.SelectedValue + "-" + ddl_search_base_month.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_base_year.SelectedValue = kw1.Substring(0, 4).ToString();
						ddl_search_base_month.SelectedValue = kw1.Substring(5, 2).ToString();
					}					
					break;
				case "SEARCH":
					kw1 = ddl_search_base_year.SelectedValue + "-" + ddl_search_base_month.SelectedValue;
					break;
			}
		}		

		#endregion

		#region 마스터 Method (SetBaseYear, SetYearlyRegYnList)

		//기준년도 설정
		private void SetBaseYear()
		{
			ddl_search_base_year.Items.Clear();

			int li_f_year = Convert.ToInt32(SEARCH_Y_MIN);
			int li_t_year = Convert.ToInt32(DateUtil.GetYearEx(1, "yyyy"));
			for (int i = li_f_year; i <= li_t_year; i++)
			{
				string ls_year = i.ToString();
				ddl_search_base_year.Items.Add(new ListItem(ls_year, ls_year));
			}

			ddl_search_base_year.SelectedValue = DateUtil.GetYearEx(0, "yyyy"); // 기본값은 현재년월
			ddl_search_base_month.SelectedValue = DateUtil.GetMonthEx(0, "MM");
		}

		//연도별 예산등록현황
		private void SetYearlyRegYnList()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			string ls_data = "";

			lo_dp.AddProperty("ls_base_year", typeof(string), kw1.Substring(0, 4));
			
			using (Mny1013m_NT _Mny1013m_NT = new Mny1013m_NT())
			{
				lo_ds.Merge(_Mny1013m_NT.GetYearlyRegYnList(lo_dp));
			}
			
			for (int i=0; i<DataSetUtil.GetRowCount(lo_ds, "UPDMS_MNY_BUDGET"); i++ )
			{
				string ls_reg_yn = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_BUDGET", i, "Reg_Yn") == "Y" ? "month_box_y" : "month_box_n";
				string ls_base_month = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_BUDGET", i, "Base_Month");
				string ls_month_label = DataSetUtil.GetFldStr(lo_ds, "UPDMS_MNY_BUDGET", i, "Month_Label");

				ls_data += "<span class=\"" + ls_reg_yn + "\" title=\"" + ls_month_label + "월\" onclick=\"doSearch('" + ls_base_month + "')\">" + ls_month_label + "</span>&nbsp;";
			}
			
			lbl_reg_yn_list.Text = ls_data;
		}

		#endregion

		#region 마스터 Method (SetPrevNextMonth, SetEnabledMonthBtn, SetThisMonth)

		//이전달, 다음달버튼 누르면
		private void SetPrevNextMonth(int pi_month_cnt)
		{
			string ls_ym = ddl_search_base_year.SelectedValue + "-" + ddl_search_base_month.SelectedValue;
			string ls_calc_ym = DateUtil.GetCalcMonth(ls_ym, pi_month_cnt, "yyyy-MM");

			if (WebControlUtil.CheckDdlValue(ddl_search_base_year, ls_calc_ym.Substring(0, 4).ToString()))
			{
				ddl_search_base_year.SelectedValue = ls_calc_ym.Substring(0, 4).ToString();
				ddl_search_base_month.SelectedValue = ls_calc_ym.Substring(5, 2).ToString();
			}

			//버튼처리
			SetEnabledMonthBtn();
		}

		//이전달, 다음달버튼 처리
		private void SetEnabledMonthBtn()
		{
			ibtn_prev_month.Enabled
				= (ddl_search_base_year.SelectedIndex == 0 && ddl_search_base_month.SelectedIndex == 0) ? false : true;

			ibtn_next_month.Enabled
				= (ddl_search_base_year.SelectedIndex == ddl_search_base_year.Items.Count - 1 && ddl_search_base_month.SelectedIndex == 11) ? false : true;
		}

		//당월설정
		private void SetThisMonth()
		{
			string ls_this_ym = DateUtil.GetNow("yyyy-MM");
			ddl_search_base_year.SelectedValue = ls_this_ym.Substring(0, 4).ToString();
			ddl_search_base_month.SelectedValue = ls_this_ym.Substring(5, 2).ToString();
			SetEnabledMonthBtn();
		}

		#endregion

		#region 디테일 Method (SyncBudgetData, ResetTotal, SetConfirmYn)

		//이전 예산 가져와서 바인딩
		private void SyncBudgetData(string ls_control)
		{
			for (int i=0; i < gv_pre_budget.Rows.Count; i++)
			{
				Label lbl_pre_data = (Label)gv_pre_budget.Rows[i].FindControl(ls_control);
				TextBox txt_amount = (TextBox)GridView1.Rows[i].FindControl("txt_amount");
				DropDownList ddl_confirm_yn = (DropDownList)GridView1.Rows[i].FindControl("ddl_confirm_yn");

				//확정된 데이터는 덮어쓰지 않음
				if (ddl_confirm_yn.SelectedValue == "N")
				{
					txt_amount.Text = lbl_pre_data.Text;
				}
			}

			//합계
			ResetTotal();
		}

		//합계
		private void ResetTotal()
		{
			decimal ld_total = 0;

			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				TextBox txt_amount = (TextBox)GridView1.Rows[i].FindControl("txt_amount");

				ld_total += Convert.ToDecimal(ConversionUtil.RemoveComma(txt_amount.Text));
			}

			GridView1.FooterRow.Cells[6].Text = ld_total.ToString("#,###,##0");
		}
		
		//일괄확정
		private void SetConfirmYn(string ls_confirm)
		{
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				DropDownList ddl_confirm_yn = (DropDownList)GridView1.Rows[i].FindControl("ddl_confirm_yn");

				ddl_confirm_yn.SelectedValue = ls_confirm;
			}
		}

		#endregion

		#region CRUD (SelectProcess, InsertProcess, SearchProcess)

		//이전 예산조회
		private void SetPreBudgetList()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색파라미터
			string ls_pre_1_month_ym = DateUtil.GetCalcMonth(kw1, -1, "yyyy-MM");
			string ls_pre_3_month_ym = DateUtil.GetCalcMonth(kw1, -3, "yyyy-MM");
			string ls_pre_12_month_ym = DateUtil.GetCalcMonth(kw1, -12, "yyyy-MM");

			lo_dp.AddProperty("ls_pre_1_month_ym", typeof(string), ls_pre_1_month_ym);
			lo_dp.AddProperty("ls_pre_3_month_ym", typeof(string), ls_pre_3_month_ym);
			lo_dp.AddProperty("ls_pre_12_month_ym", typeof(string), ls_pre_12_month_ym);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Mny1013m_NT _Mny1013m_NT = new Mny1013m_NT())
			{
				lo_ds.Merge(_Mny1013m_NT.GetPreBudgetList(lo_dp));
			}

			gv_pre_budget.DataSource = lo_ds;
			gv_pre_budget.DataBind();
		}

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_base_ym", typeof(string), kw1);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Mny1013m_NT _Mny1013m_NT = new Mny1013m_NT())
			{
				lo_ds.Merge(_Mny1013m_NT.SelectProcess(lo_dp));
			}

			GridView1.DataSource = lo_ds;
			GridView1.DataBind();

			for (int i = 0; i < DataSetUtil.GetRowCount(lo_ds, "UPDMS_MNY_BUDGET"); i++)
			{
				TextBox txt_amount = (TextBox)GridView1.Rows[i].FindControl("txt_amount");

				//어트리뷰트 추가
				string ls_attr = "document.form1." + txt_amount.UniqueID + ".value=addComma(document.form1." + txt_amount.UniqueID + ".value);";
				txt_amount.Attributes.Add("onkeyup", ls_attr);
			}
		}

		//저장
		private void InsertProcess()
		{
			using (Mny1013m_RT _Mny1013m_RT = new Mny1013m_RT())
			{
				int li_return = _Mny1013m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}		

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			SetYearlyRegYnList();
			SetPreBudgetList();
			SelectProcess();
		}

		#endregion

		#region SetValue

		//SetValue
		private string SetValue()
		{
			StringBuilder sb = new StringBuilder();
			sb.Append("<UPDMS>");
						
			string ls_base_ym = ddl_search_base_year.SelectedValue + "-" + ddl_search_base_month.SelectedValue;
			
			//루프를 돌면서 저장할 데이터를 XML로 만듬
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
				string ls_account = GridView1.DataKeys[i].Values["Account"].ToString();
				TextBox txt_amount = (TextBox)GridView1.Rows[i].FindControl("txt_amount");
				DropDownList ddl_confirm_yn = (DropDownList)GridView1.Rows[i].FindControl("ddl_confirm_yn");
				
				sb.Append("<UPDMS_MNY_BUDGET>");
				sb.Append("<Flag>I</Flag>");
				sb.Append("<Seq>" + ls_seq + "</Seq>");
				sb.Append("<Base_Ym>" + ls_base_ym + "</Base_Ym>");
				sb.Append("<Account>" + ls_account + "</Account>");
				sb.Append("<Amount>" + ConversionUtil.ExtractNumberStr(ConversionUtil.DefaultValue(txt_amount.Text, "0")) + "</Amount>");
				sb.Append("<Confirm_Yn>" + ddl_confirm_yn.SelectedValue + "</Confirm_Yn>");				
				sb.Append("<Create_User>" + USER_ID + "</Create_User>");
				sb.Append("<Update_User>" + USER_ID + "</Update_User>");
				sb.Append("</UPDMS_MNY_BUDGET>");
			}
			sb.Append("</UPDMS>");

			//Base.AppFramework.SMEventLog.WriteDataLog("SetValue()", sb.ToString());

			return sb.ToString();
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			//SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}
		
		#endregion	

		#region GridView이벤트

		//RowDataBound
		protected void gv_pre_budget_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);				

				switch (gv_pre_budget.DataKeys[e.Row.RowIndex].Values["Class"].ToString())
				{
					case "AA002"://지출
						e.Row.Cells[1].Attributes.Add("class", "color_darkred");
						break;
					case "AA003"://저축
						e.Row.Cells[1].Attributes.Add("class", "color_darkgreen");
						break;
					default:
						e.Row.Cells[1].Attributes.Add("class", "color_darkred");
						break;
				}
			}

			//합계
			ld_pre_1_m += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Pre_Month"));
			ld_pre_1_y += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Pre_Year"));
			ld_pre_3_m_avg += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Pre_3_Month_Avg"));
			ld_pre_12_m_avg += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Pre_12_Month_Avg"));

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Visible = false;	//0.Class
				e.Row.Cells[1].Text = "Total";
				e.Row.Cells[1].Attributes.Add("class", "total");
				e.Row.Cells[1].ColumnSpan = 2;
				e.Row.Cells[2].Visible = false;	//2.Account
				e.Row.Cells[3].Visible = false;	//3.Account_Nm
				e.Row.Cells[4].Text = ld_pre_1_m.ToString("#,###,##0");
				e.Row.Cells[4].Attributes.Add("class", "money");				
				e.Row.Cells[5].Text = ld_pre_1_y.ToString("#,###,##0");
				e.Row.Cells[5].Attributes.Add("class", "money");
				e.Row.Cells[6].Text = ld_pre_3_m_avg.ToString("#,###,##0");
				e.Row.Cells[6].Attributes.Add("class", "money");
				e.Row.Cells[7].Text = ld_pre_12_m_avg.ToString("#,###,##0");
				e.Row.Cells[7].Attributes.Add("class", "money");
			}

			//머지
			SMGridView sGv = new SMGridView();
			sGv.RowSpanGridView(gv_pre_budget, 1);//1.Class_Nm
		}

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				switch (GridView1.DataKeys[e.Row.RowIndex].Values["Class"].ToString())
				{
					case "AA002"://지출
						e.Row.Cells[3].Attributes.Add("class", "color_darkred");
						break;
					case "AA003"://저축
						e.Row.Cells[3].Attributes.Add("class", "color_darkgreen");
						break;
					default:
						e.Row.Cells[3].Attributes.Add("class", "color_darkred");
						break;
				}
			}

			//합계
			ld_amount += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"));

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Visible = false;	//Seq
				e.Row.Cells[1].Text = "Total";
				e.Row.Cells[1].Attributes.Add("class", "total label_btn");
				e.Row.Cells[1].Attributes.Add("onclick", "resetTotal();");
				e.Row.Cells[1].ColumnSpan = 3;
				e.Row.Cells[2].Visible = false;
				e.Row.Cells[3].Visible = false;
				e.Row.Cells[4].Visible = false;
				e.Row.Cells[5].Visible = false;
				e.Row.Cells[6].Text = ld_amount.ToString("#,###,##0");
				e.Row.Cells[6].Attributes.Add("class", "money");
				e.Row.Cells[7].Text = "";
				e.Row.Cells[7].Attributes.Add("class", "none");
			}

			//머지
			SMGridView sGv = new SMGridView(this.Page, ref GridView1);
			sGv.RowSpanGridView(GridView1, 1);
			sGv.RowSpanGridView(GridView1, 3);
		}
		
		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SetEnabledMonthBtn();
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			InsertProcess();
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_base_ym", typeof(string), kw1);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Mny1013m_NT _Mny1013m_NT = new Mny1013m_NT())
			{
				lo_ds.Merge(_Mny1013m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//전월
		protected void lbtn_sync_pre_1_m_Click(object sender, EventArgs e)
		{
			SyncBudgetData("lbl_pre_1_m");
		}

		//전년도 당월
		protected void lbtn_sync_pre_1_y_Click(object sender, EventArgs e)
		{
			SyncBudgetData("lbl_pre_1_y");
		}

		//3개월평균
		protected void lbtn_sync_pre_3_m_avg_Click(object sender, EventArgs e)
		{
			SyncBudgetData("lbl_pre_3_m_avg");
		}

		//12개월평균
		protected void lbtn_sync_pre_12_m_avg_Click(object sender, EventArgs e)
		{
			SyncBudgetData("lbl_pre_12_m_avg");
		}

		//확정여부 - Y
		protected void lbtn_confirm_y_Click(object sender, EventArgs e)
		{
			SetConfirmYn("Y");
		}

		//확정여부 - N
		protected void lbtn_confirm_n_Click(object sender, EventArgs e)
		{
			SetConfirmYn("N");
		}

		//합계
		protected void lbtn_reset_total_Click(object sender, EventArgs e)
		{
			ResetTotal();
		}

		//이전달
		protected void ibtn_prev_month_Click(object sender, EventArgs e)
		{
			SetPrevNextMonth(-1);
			SearchProcess();
		}

		//다음달
		protected void ibtn_next_month_Click(object sender, EventArgs e)
		{
			SetPrevNextMonth(1);
			SearchProcess();
		}

		//당월
		protected void ibtn_this_month_Click(object sender, EventArgs e)
		{
			SetThisMonth();
			SearchProcess();
		}

		#endregion		
			
	}
}
